﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Zero.UControl.Component
{
    /// <summary>
    /// RollingNumber.xaml 的交互逻辑
    /// </summary>
    public partial class RollingNumber : INotifyPropertyChanged
    {

        public RollingNumber()
        {

        }

        private bool _firstLoaded = false;

        #region 依赖属性
        public double ItemHeight
        {
            get { return (double)GetValue(ItemHeightProperty); }
            set { SetValue(ItemHeightProperty, value); }
        }

        public static readonly DependencyProperty ItemHeightProperty =
            DependencyProperty.Register("ItemHeight", typeof(double), typeof(RollingNumber), new PropertyMetadata(30.0));


        public string NumStr
        {
            get { return (string)GetValue(NumStrProperty); }
            set { SetValue(NumStrProperty, value); }
        }

        public static readonly DependencyProperty NumStrProperty =
            DependencyProperty.Register("NumStr", typeof(string), typeof(RollingNumber), new PropertyMetadata(null, NumStrChanged));
        #endregion

        private static void NumStrChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            
        }

        private string _Text;
        public string Text
        {
            get { return _Text; }
            set
            {
                _Text = value;
                OnPropertyChanged(nameof(Text));

                if (!_firstLoaded)
                {
                    // 反向处理数字位
                    RollingNumberItem[] numArr = new RollingNumberItem[stackPanel.Children.Count];
                    int index = 1;
                    foreach (RollingNumberItem num in stackPanel.Children)
                        numArr[numArr.Length - index++] = num;

                    if (_Text != null)
                    {
                        int i = 0;
                        foreach (char c in _Text.Reverse())
                        {
                            double d = Convert.ToInt32(c - 48);
                            numArr[i++].Num = d;
                        }
                        // 控制数字位的显示/隐藏
                        for (int k = 0; k < i; k++) numArr[k].Visibility = Visibility.Visible;
                        for (int k = i; k < numArr.Length; k++) numArr[k].Visibility = Visibility.Collapsed;
                    }
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        protected void OnPropertyChanged(string prop) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
    }
}
